import { Component, Input, OnInit, Inject, forwardRef, ViewChild, ElementRef } from '@angular/core';

import { IonSegment } from '@ionic/angular';

import { ComItem } from '../../route/entry/com-item';
import { EventService } from '../../shared/service/event.service';
import { HttpService } from '../../shared/service/http.service';
import { AppGlobalService } from '../../shared/service/app-global.service';
import { MessageService } from "../../shared/service/message.service";
import { FirstLevel } from "../sift/firstLevel.model";
import { SiftModel } from "../sift/sift.model";
import { ChangeDetectorRef } from '@angular/core';
@Component({
  selector: 'app-button-nav-one',
  templateUrl: './button-nav-one.component.html',
  styleUrls: ['./button-nav-one.component.scss'],
})
export class ButtonNavOneComponent implements OnInit {
  @ViewChild("segment", { read: ElementRef }) private segment: ElementRef;
  @ViewChild('segment', null) ionSegment: IonSegment;
  receiverTag = 'ButtonNavOneComponentReceiver';
  subComs7: ComItem[];
  @Input() tagData: any;
  aWidth: string;
  isSelected: boolean;
  currentClickObj: any;
  currentCLickIndexTab: any;
  isRootURL: any; // 用于检查URL是否有变化
  selectedSegment = 0;
  switchBoxId = 'switchBoxId';
  currentSwitchBlockPluginId = "0";

  // 用于筛选下拉的标签
  sessionId: string;
  commonFilterTag: any;
  switchBlockTag: any; // 蜂喔app新增首页tag样式
  switchCheckedButton = '';
  siftArr: FirstLevel[]; // 筛选条件list
  siftArrtwo: any; // 循环筛选数据的数组
  siftArrthree: any; // 循环筛选数据关于事件的数组
  siftTypeArr: any; // 转让or出租
  siftWidth: any; // 宽度
  openFlag = false; // 下级列表面板是否打开
  siftObj: FirstLevel; // 筛选条件
  firstLevelList: SiftModel[]; // 第一次选中元素
  ifSecond: boolean; // 是否有二级列表
  ifLink: boolean; // 是否link
  secondLevelList: SiftModel[]; // 第一次选中元素
  selectedIndexName: any; // 选中的条件显
  selectedIndexDisplayName: any; // 选中的条件显
  currentCity: any; // 当前城市
  showName: any;
  filterType: any = "transfer";
  // 选中结果
  result: any = {
    showName: "",
    filter: {},
    order: {}
  };
  key: '';
  type: string; // 类型
  fristObj;
  siftArrPercent = '';
  showCustomPicker = false;
  appTypeCustom: any;

  // appGlobalService.openBackdrop = false; showSiftCondation
  isRefreshAfterCLickSwitchButton = false;
  refreshFilterId = "";
  constructor(
    private eventService: EventService,
    private message: MessageService,
    private httpService: HttpService,
    private appGlobalService: AppGlobalService,
    public cd: ChangeDetectorRef
  ) {
    if (this.eventService.eventEmit.listenerCount(this.receiverTag) > 0) {
      this.eventService.eventEmit.removeListener(this.receiverTag);
    }
    this.eventService.eventEmit.on(this.receiverTag, res => {
      if (localStorage.getItem(this.receiverTag + 'Tag')) {
        localStorage.removeItem(this.receiverTag + 'Tag');
        this.subComs7 = res.coms;
      }
    });

    // 有customerTab时切换
    this.eventService.eventEmit.on("buttonNavOneTabClickRefresh", (obj) => {
      const reqTag = localStorage.getItem('buttonNavOneTabClickRefreshTag');
      if (reqTag !== undefined && reqTag !== null) {
        localStorage.removeItem('buttonNavOneTabClickRefreshTag');
        // tslint:disable-next-line:radix
        // this.selectedSegment = Number.parseInt(JSON.parse(reqTag));
        this.segmentChanged(0, reqTag);

      }
    });

  }

  async segmentChanged(e: any, indexTab?) {
    this.appGlobalService.openBackdrop = false;
    let index = 0;
    if (indexTab !== undefined) {
      index = indexTab;
    } else {
      if (e.detail.value === 'NaN') { return; }
      index = e.detail.value;
    }
    // console.log('msg----->' + index);
    if (this.appTypeCustom === 'LJ') {
      localStorage.setItem('buttonNavOneTabIndex', '' + index);
      this.changeNearButtonCss(index, this.tagData.data.length + '');
    }

    try {
      const segmentButton = this.segment.nativeElement.children[index];
      segmentButton.scrollIntoView({
        behavior: 'smooth',
        inline: 'center',
        block: 'nearest'
      });
    } catch (error) {

    }
    await this.showIndicator();
    if (this.tagData.data) {
      // 清除下拉选择框 fixed by andrew.wen for bug-view-4384.html
      this.result.filter = {};
      this.result.order = {};
      this.httpService.post('application/part',
        {
          viewId: this.tagData.data[index].partLink.target,
          sessionId: localStorage.getItem("sessionId"),
          params: this.tagData.data[index].partLink.params
        }, (res: any) => {
          if (res) {
            const tmpData = JSON.parse(res.script);
            if (tmpData.tags[0].style === 'tag.FilterTagLogic') {
              this.isRefreshAfterCLickSwitchButton = (tmpData.tags[0].id !== undefined && tmpData.tags[0].id !== "");
              if (tmpData.tags[0].id) {
                this.refreshFilterId = tmpData.tags[0].id;
              }
              this.commonFilterTag = tmpData.tags.shift();
              this.initFilterTag(this.commonFilterTag);
            } else {
              this.commonFilterTag = null;
            }
            // 拦截完filterTag在拦截switchBlockTag 这个tag
            if (tmpData.tags[0].name === 'switchBlockTag') {
              // this.switchBoxId += new Date().getTime();
              this.switchBlockTag = tmpData.tags.shift();
              if (!this.result.opportunity_plugin_id || !this.result.plugin_type_id) {
                Object.assign(this.result, this.switchBlockTag.data[0].params);
              }
              // tslint:disable-next-line:prefer-for-of
              for (let i = 0; i < this.switchBlockTag.data.length; i++) {
                const element = this.switchBlockTag.data[i];
                if (element.selected === "true") {
                  this.switchCheckedButton = element.label;
                  if (i !== 0) {
                    // 获取元素 触发请求
                    // setTimeout(() => {
                    const array = document.getElementsByClassName('home-switch-box-button-' + this.switchBlockTag.style);
                    // tslint:disable-next-line:prefer-for-of
                    for (let k = 0; k < array.length; k++) {
                      const subjectK = array[k] as HTMLElement;
                      if (element.id === subjectK.id) {
                        // subjectK.click();
                        subjectK.click();
                      }
                    }
                    // }, 100);
                    // Object.assign(this.result.filter, element.params.filter);
                    // const paramKeys = Object.keys(element.params);
                    // // tslint:disable-next-line:prefer-for-of
                    // for (let j = 0; j < paramKeys.length; j++) {
                    //   // tslint:disable-next-line:no-shadowed-variable
                    //   const keyName = paramKeys[j];
                    //   if (keyName !== 'filter') {
                    //     const newParamObj = {};
                    //     newParamObj[keyName] = element.params[keyName];
                    //     Object.assign(this.result, newParamObj);
                    //   }
                    // }
                    // this.requestData(element);
                  }
                  break;
                }

              }
            } else {
              this.switchBlockTag = null;
            }
            // 发送事件
            const eventEmitObj = { data: tmpData, receiverTag: this.receiverTag };
            localStorage.setItem('generatedComItemWithBufferTag', JSON.stringify(eventEmitObj));
            this.eventService.eventEmit.emit('generatedComItemWithBuffer', '');
            // 修复默认选中不正确bug
            localStorage.setItem('customTabRefreshTag', JSON.stringify(index));
            this.eventService.eventEmit.emit('customTabRefresh', '');
          }
        });
    }

  }

  showIndicator() {
    const len = this.tagData.data.length;
    // for (let i = 0; i < len; i++) {
    //     document.getElementById('segmentIndicator' + i).style.display = "none";
    // }

    // bug: #574 切换tab页后应从当前tab的第一条信息开始展示
    const contents = document.querySelectorAll('ion-content');
    const ele = document.querySelector('ion-content #scrollContent');
    let target = null;
    contents.forEach(item => {
      if (this.isChildOf(ele, item)) {
        target = item;
      }
    });
    target.getScrollElement().then(e => {
      if (e.scrollTop >= document.getElementById('scrollContent').offsetTop) {
        target.scrollToPoint(0, document.getElementById('scrollContent').offsetTop); // height + 44px
      }
    });
  }
  /**
   * 判断是否子节点
   * @param child 子节点
   * @param parent 父节点
   */
  isChildOf(child, parent) {
    let parentNode;
    if (child && parent) {
      parentNode = child.parentNode;
      while (parentNode) {
        if (parent === parentNode) {
          return true;
        }
        parentNode = parentNode.parentNode;
      }
    }
    return false;
  }
  async ngOnInit() {
    const that = this;
    try {
      const bodyStyles = window.getComputedStyle(document.body);
      this.appTypeCustom = bodyStyles.getPropertyValue('--appTypeCustom').trim().replace('"', '').replace('"', '');
      this.sessionId = localStorage.getItem("sessionId");
      this.aWidth = 100 / this.tagData.data.length + '%';
      const cDataObj = this.tagData.currentData;
      this.selectedSegment = +this.tagData.currentTab;

      if (cDataObj !== undefined) {
        const tags = cDataObj.tags;
        if (tags !== undefined && tags.length > 0) {


          // const tmpData = this.tagData.currentData;
          // if (tmpData.tags[0].style === 'tag.FilterTagLogic') {
          //   this.commonFilterTag = tmpData.tags.shift();
          //   this.initFilterTag(this.commonFilterTag);
          // } else {
          //   this.commonFilterTag = null;
          // }

          // 如果返回的currentData里面有filterTag拦截并处理
          if (cDataObj.tags.length > 0) {
            if (cDataObj.tags[0].style === 'tag.FilterTagLogic') {
              this.isRefreshAfterCLickSwitchButton = (cDataObj.tags[0].id !== undefined && cDataObj.tags[0].id !== "");
              if (cDataObj.tags[0].id) {
                this.refreshFilterId = cDataObj.tags[0].id;
              }
              this.commonFilterTag = this.tagData.currentData.tags.shift();
              this.initFilterTag(this.commonFilterTag);
            } else {
              this.commonFilterTag = null;
            }

            // 拦截完filterTag在拦截switchBlockTag 这个tag
            if (this.tagData.currentData.tags[0].name === 'switchBlockTag') {

              // this.switchBoxId += new Date().getTime();
              this.switchBlockTag = this.tagData.currentData.tags.shift();
              if (!this.result.opportunity_plugin_id || !this.result.plugin_type_id) {
                Object.assign(this.result, this.switchBlockTag.data[0].params);
              }
              // tslint:disable-next-line:prefer-for-of
              for (let index = 0; index < this.switchBlockTag.data.length; index++) {
                const element = this.switchBlockTag.data[index];
                if (element.selected === "true") {
                  // Object.assign(this.result.filter, element.params.filter);
                  // const paramKeys = Object.keys(element.params);
                  // tslint:disable-next-line:prefer-for-of
                  // for (let j = 0; j < paramKeys.length; j++) {
                  //   // tslint:disable-next-line:no-shadowed-variable
                  //   const keyName = paramKeys[j];
                  //   if (keyName !== 'filter') {
                  //     const newParamObj = {};
                  //     newParamObj[keyName] = element.params[keyName];
                  //     Object.assign(this.result, newParamObj);
                  //   }
                  // }
                  if (index !== 0) {
                    // this.requestData(element);
                    // 获取元素 触发请求
                    setTimeout(() => {
                      const array = document.getElementsByClassName('home-switch-box-button-' + this.switchBlockTag.style);
                      // tslint:disable-next-line:prefer-for-of
                      for (let k = 0; k < array.length; k++) {
                        const subjectK = array[k] as HTMLElement;
                        if (element.id === subjectK.id) {
                          // subjectK.click();
                          subjectK.click();
                        }
                      }
                    }, 100);
                  }
                  // this.switchCheckedButton = element.label;
                  // 初始化时带参数
                  break;
                }
              }
            } else {
              this.switchBlockTag = null;
            }
          }




          // 处理筛选标签
          // #task-view-916
          if (this.tagData.refresh) {
            this.tagData.currentData.isPullToRefresh = this.tagData.refresh;
          }

          // tmpData.isPullToRefresh = true;
          // 发送事件
          const eventEmitObj = { data: this.tagData.currentData, receiverTag: this.receiverTag };
          localStorage.setItem('generatedComItemWithBufferTag', JSON.stringify(eventEmitObj));
          this.eventService.eventEmit.emit('generatedComItemWithBuffer', '');

          // that.httpService.post('application/part',
          //   {
          //     viewId: this.tagData.data[0].partLink.target,
          //     sessionId: localStorage.getItem("sessionId"),
          //     params: this.tagData.data[0].partLink.params
          //   }, (res: any) => {
          //     if (res) {
          //       const tmpData = JSON.parse(res.script);
          //       if (tmpData.tags[0].style === 'tag.FilterTagLogic') {
          //         this.commonFilterTag = tmpData.tags.shift();
          //         this.initFilterTag(this.commonFilterTag);
          //       } else {
          //         this.commonFilterTag = null;
          //       }

          //       // 处理筛选标签
          //       // #task-view-916
          //       if (this.tagData.refresh) {
          //         tmpData.isPullToRefresh = this.tagData.refresh;
          //       }
          //       // tmpData.isPullToRefresh = true;
          //       // 发送事件
          //       const eventEmitObj = { data: tmpData, receiverTag: this.receiverTag };
          //       localStorage.setItem('generatedComItemWithBufferTag', JSON.stringify(eventEmitObj));
          //       this.eventService.eventEmit.emit('generatedComItemWithBuffer', '');
          //     }
          //   });
        }
      }
      if (this.appTypeCustom === 'LJ') {
        setTimeout(() => {
          this.changeNearButtonCss(this.tagData.currentTab, this.tagData.data.length + '');
        }, 300);
      }
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }

  changeNearButtonCss(currentTab, totalTab) {
    try {
      for (let index = 0; index < totalTab; index++) {
        const arrayIndex = 'ion-segment-btn-home' + index;
        const tempDiv = document.getElementById(arrayIndex).children[0] as HTMLElement;
        tempDiv.setAttribute('style', 'width:calc( 100vw / ' + totalTab + ');');
        if (index + '' === currentTab) {
          continue;
        } else {
          const tempId = 'ion-segment-btn-home' + index;
          const tempButton = document.getElementById(tempId) as HTMLElement;
          tempButton.setAttribute('style', 'border-radius: 0rem 0rem 0rem 0rem;');
        }
      }
      // 第一个
      if (currentTab === '0') {
        const secondButtonId = 'ion-segment-btn-home' + 1;
        const secondButton = document.getElementById(secondButtonId) as HTMLElement;
        secondButton.setAttribute('style', 'border-radius: 0rem 0rem 0rem 0.5rem;');

        // 最后一个
      } else if (currentTab === totalTab) {
        const beforeLastButtonId = 'ion-segment-btn-home' + (totalTab - 1);
        const beforeLastButton = document.getElementById(beforeLastButtonId) as HTMLElement;
        beforeLastButton.setAttribute('style', 'border-radius: 0rem 0rem 0.5rem 0rem;');
      } else {
        const beforeCurrentButtonId = 'ion-segment-btn-home' + (currentTab - 1);
        const beforeCurrentButton = document.getElementById(beforeCurrentButtonId) as HTMLElement;
        beforeCurrentButton.setAttribute('style', 'border-radius: 0rem 0rem 0.5rem 0rem;');
        // tslint:disable-next-line:radix
        const num = parseInt(currentTab) + 1;
        const afterCurrentButtonId = 'ion-segment-btn-home' + num;
        const afterCurrentButton = document.getElementById(afterCurrentButtonId) as HTMLElement;
        afterCurrentButton.setAttribute('style', 'border-radius: 0rem 0rem 0rem 0.5rem;');
      }
    } catch (error) {
    }
  }



  initFilterTag(commonFilterTag, callbackFunction?) {
    try {
      this.siftArrtwo = [];
      this.siftArrthree = [];
      this.siftArr = [];
      // filterItems里queryTypetype为dateFilter的类型特殊，故将该类型剔除，重新组装数据siftArrtwo在视图层循环li部分，而queryTypetype为dateFilter的类型数据储存在siftArrthree;
      /* this.siftArr = this.tagData.filterItems; */
      this.commonFilterTag.filterItems.forEach(element => {
        this.siftArr.push(element);
      });

      // tslint:disable-next-line:prefer-for-of
      for (let i = 0; i < this.siftArr.length; i++) {
        if (this.siftArr[i].dropDownList) {

          if (this.siftArr[i].dropDownList.displayName) {
            if (this.appTypeCustom !== 'LJ') {
              this.siftArr[i].title = this.siftArr[i].dropDownList.displayName;
            }
          }
          if (this.siftArr[i].type === "filter") {
            this.result.filter[this.siftArr[i].name] = this.siftArr[i].dropDownList.value;
          }
        } else if (this.siftArr[i].type === "link" && this.siftArr[i].display && this.siftArr[i].display.displayName.length) {
          this.siftArr[i].title = this.siftArr[i].display.displayName;
          this.result.filter[this.siftArr[i].name] = this.siftArr[i].display.value;
        }
      }
      if (this.commonFilterTag.filterType) {
        this.siftTypeArr = this.commonFilterTag.filterType;
        if (this.siftTypeArr.length > 0) {
          this.siftWidth = ((100 - this.siftTypeArr.length * 2) / this.siftTypeArr.length) + "%";
        }
        this.result.showName = this.showName;
      }
      callbackFunction();
    } catch (error) {

    }

  }

  // 初始化二级筛选栏tag
  initSwitchBlockTag(switchBlockTag) {
    try {


    } catch (error) {

    }

  }

  switchBlockClick(item, className) {
    try {
      // 点击二级切换按钮之后初始化下拉筛选列表
      this.appGlobalService.openBackdrop = false;
      item.selected = 'true';
      const nameId = 'home-switch-box-button-' + className;
      const array = document.getElementsByClassName(nameId);
      // tslint:disable-next-line:prefer-for-of
      for (let index = 0; index < array.length; index++) {
        const element = array[index];
        if (item.id === element.id) {
          this.addClass(element, "switch-checked-" + className);
          this.addClass(element.children[0], "home-checked-font-" + className);
          //  参数变动 Object.assign(this.result.filter, item.params);
          // TODO  Object.assign(this.result.filter, item.params.filter);
          const paramKeys = Object.keys(item.params);
          // tslint:disable-next-line:prefer-for-of
          for (let j = 0; j < paramKeys.length; j++) {
            // tslint:disable-next-line:no-shadowed-variable
            const keyName = paramKeys[j];
            if (keyName !== 'filter') {
              const newParamObj = {};
              newParamObj[keyName] = item.params[keyName];
              Object.assign(this.result, newParamObj);
            } else if (keyName === "filter") {
              this.result.filter = item.params.filter;
            }
          }
        } else {
          this.removeClass(element, "switch-checked-" + className);
          this.removeClass(element.children[0], "home-checked-font-" + className);
        }
      }
      if (item.params.plugin_type_id) {
        this.currentSwitchBlockPluginId = item.params.plugin_type_id;
        this.appGlobalService.openBackdrop = false;
      }

      this.requestData(item);
    } catch (error) {

    }
  }

  requestData(item) {
    try {
      if (this.isRefreshAfterCLickSwitchButton) {
        const params = {
          content: item.params, // { filter: this.result.filter },
          id: this.refreshFilterId,
          sessionId: this.sessionId
        };
        this.httpService.post("application/submit", params, res => {
          // this.openFlag = true;
          // this.appGlobalService.openBackdrop = true;
          // this.firstLevelList = this.secondLevelList = []; // 初始化
          // this.firstLevelList = res.data.data;
          // console.log('msg----->' + JSON.stringify(res));
          const filterItems = JSON.parse(res.data.filterItems);
          const filterTag = { filterItems };
          this.commonFilterTag = filterTag;
          this.initFilterTag(filterTag, () => {
            this.getResult({ active: true, displayName: '', value: this.result.filter[this.key] });
          });

        }, err => {
          console.log('error----->' + JSON.stringify(err));
          // this.firstLevelList = this.secondLevelList = []; // 初始化
        });
      } else {
        this.getResult({ active: true, displayName: '', value: this.result.filter[this.key] });
      }

    } catch (error) {
    }

  }

  /**
   * 添加class
   */
  addClass(ele, value) {
    if (value) {
      let curValue = this.getClass(ele);
      if (curValue.indexOf(value) === -1) {
        curValue = curValue + " " + value;
      }
      ele.setAttribute("class", curValue.trim());
    }
  }
  /**
   * 删除class
   */
  removeClass(ele, value) {
    if (value) {
      let curValue = this.getClass(ele);
      if (curValue.indexOf(value) > -1) {
        curValue = (" " + curValue + " ").replace(" " + value + " ", " ");
      }
      ele.setAttribute("class", curValue.trim());
    }
  }
  /**
   * 元素是否存在值为@{value}的class
   */
  hasClass(ele, value) {
    let has = false;
    if (value) {
      const curValue = this.getClass(ele);
      if (curValue.indexOf(value) > -1) {
        has = true;
      }
    }
    return has;
  }

  /**
   * 获取class
   */
  getClass(elem) {
    return elem.getAttribute && elem.getAttribute("class") || "";
  }



  // 新的样式用于点击筛选按钮
  siftEventForNewStyle(obj) {
    try {


      const currentPath = localStorage.getItem("tabPath");
      // add by andrew.wen for 首页的筛选需要特殊处理
      if (currentPath !== null && currentPath === 'home/tab1') {
        // tslint:disable-next-line:no-string-literal
        if (
          document.getElementById('topSegment').getAttribute('isSticky') === null ||
          document.getElementById('topSegment').getAttribute('isSticky') === 'false') {
          let totalScrollHeight = 0;
          const dynamicScrollTop = localStorage.getItem('dynamicScrollTop');
          if (dynamicScrollTop === null || dynamicScrollTop === '0') {
            if (document.getElementsByClassName('buttonNavOneClassName')) {
              // tslint:disable-next-line:no-string-literal
              totalScrollHeight += document.getElementsByClassName('buttonNavOneClassName')[0]['offsetTop'];
              localStorage.setItem('tab1ScrollToBottomTag', totalScrollHeight + '');
            }
            this.eventService.eventEmit.emit('tab1ScrollToBottom', '1');
          } else {
            // tslint:disable-next-line:no-string-literal
            const subjectHeight = document.getElementsByClassName('buttonNavOneClassName')[0]['offsetTop'];
            // tslint:disable-next-line:radix
            totalScrollHeight = subjectHeight - parseInt(dynamicScrollTop);
          }

          // 如果可滑动距离不足则需要手动添加滑动距离
          if (document.getElementsByClassName('new-container-box')) {
            // tslint:disable-next-line:no-string-literal
            const bottomBoxOffsetBottom = document.getElementsByClassName('new-container-box')[0]['offsetTop']
              // tslint:disable-next-line:no-string-literal
              + document.getElementsByClassName('new-container-box')[0]['offsetHeight'];
            const screenHeight = window.innerHeight;
            if ((bottomBoxOffsetBottom - screenHeight) < totalScrollHeight) {
              document.getElementsByClassName('new-container-box')[0].setAttribute('style', '0');
              // todo 为了适配安卓高分辨率手机 一加7 2380 * 1080 需要新增1个导航栏的高度
              const resetHeight = (totalScrollHeight - (bottomBoxOffsetBottom - screenHeight)) + 44;
              const bottom = 'margin-bottom:' + resetHeight + 'px';
              document.getElementsByClassName('new-container-box')[0].setAttribute('style', bottom);
            }

          }

          localStorage.setItem('tab1ScrollToBottomTag', totalScrollHeight + '');
          this.eventService.eventEmit.emit('tab1ScrollToBottom', '1');
        }
      }
      setTimeout(() => {
        const pos = JSON.parse(localStorage.getItem("position"));
        this.key = obj.name;
        this.type = obj.type;

        if (this.type === 'link' && obj.display.link) {
          this.ifLink = true;
          this.openFlag = false;
          this.siftObj = obj;
          this.appGlobalService.openBackdrop = false;
          // this.appGlobalService.openBackdrop = false;
        } else {
          this.ifSecond = !!obj.dropDownList.dropDownList;
          if (this.siftObj === obj) {
            this.openFlag = !this.openFlag;
            this.appGlobalService.openBackdrop = !this.appGlobalService.openBackdrop;

          } else {
            this.siftObj = obj;
            // this.firstLevelList = this.secondLevelList = []; // 初始化
            this.siftArr.forEach(v => {
              v.active = v === obj;
            });
            const params = {
              content: {
                code: obj.ifCode && obj.ifCode + "" === "1" ? pos.code : 0
              },
              id: obj.dropDownList.id,
              sessionId: this.sessionId
            };
            if (this.ifSecond) {
              this.httpService.post("application/submit", params, res => {
                this.openFlag = true;
                this.appGlobalService.openBackdrop = true;
                this.firstLevelList = this.secondLevelList = []; // 初始化
                this.firstLevelList = res.data.data;
              }, err => {
                this.firstLevelList = this.secondLevelList = []; // 初始化
              });
            } else {
              this.openFlag = true;
              this.appGlobalService.openBackdrop = true;
              // 查看当前筛选列表item:
              // 初始化commonFilter控件中排序的值
              // if (item.label === "找店") {
              //   this.siftArr[3].dropDownList.item[2]['hide'] = true;
              //   this.siftArr[3].dropDownList.item[3]['hide'] = true;
              // } else {
              //   delete this.siftArr[3].dropDownList.item[2]['hide'];
              //   delete this.siftArr[3].dropDownList.item[3]['hide'];
              // }
              this.firstLevelList = this.siftObj.dropDownList.item;

            }
          }
        }
        if (this.currentSwitchBlockPluginId === "3") {
          if (this.firstLevelList.length >= 4) {
            // tslint:disable-next-line:no-string-literal
            this.firstLevelList[2]['hide'] = '1';
            // tslint:disable-next-line:no-string-literal
            this.firstLevelList[3]['hide'] = '1';
          }
        } else {
          if (this.firstLevelList && this.firstLevelList.length >= 4) {
            // tslint:disable-next-line:no-string-literal
            delete this.firstLevelList[2]['hide'];
            // tslint:disable-next-line:no-string-literal
            delete this.firstLevelList[3]['hide'];
          }
        }
      }, 100);
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }



  get(obj) {
    const params = {
      pageId: obj.target,
      params: obj.params,
      sessionId: localStorage.getItem('sessionId')
    };
    this.appGlobalService.goToForward(params);
  }

  // 点击第一层下拉列表
  chooseFirstEvent(obj) {

    if (this.ifSecond) {
      const params = {
        content: {
          code: obj.value
        },
        id: this.siftObj.dropDownList.dropDownList.id,
        sessionId: this.sessionId
      };
      this.httpService.post("application/submit", params, res => {
        if (obj.displayName === "全部") {
          this.secondLevelList = [];
          this.secondLevelList.push(res.data.data[0]);
        } else {
          this.secondLevelList = res.data.data;
        }
      });
    } else {
      this.openFlag = false;
      this.appGlobalService.openBackdrop = false;
      this.siftArr.forEach(v => {
        if (v === this.siftObj) {
          v.title = obj.displayName;
        }
      });
      // if (obj.displayName === "自定义") {
      //   obj.min = this.minArea;
      //   obj.max = this.maxArea;
      // } else {
      //   this.minArea = this.maxArea = "";
      // }
      // obj.min = this.minArea;
      // obj.max = this.maxArea;

      if (this.commonFilterTag.displayIndex && this.commonFilterTag.displayIndex.length > 0) {
        // 获取第一列后面显示隐藏的条件
        let isfirstCol = false;
        this.commonFilterTag.displayIndex.forEach(element => {
          // 选中的不是上一次的条件
          if (element.displayName === obj.displayName && element.displayName !== this.selectedIndexDisplayName) {
            isfirstCol = true;
            this.selectedIndexName = element.indexName;
            this.selectedIndexDisplayName = element.displayName;

            // 重置筛选条件
            this.resSetFilter();
            // this.key = obj.name;
            // this.result.filter[obj.name] = obj.value;
            // obj.title = element.displayName;
            this.getResult(obj);
          } else if (element.displayName === obj.displayName && element.displayName === this.selectedIndexDisplayName) {
            isfirstCol = true;
          }
        });
        //  不是第一列
        if (!isfirstCol) {
          this.getResult(obj);
        }
      } else {
        this.getResult(obj);
      }

    }
    this.firstLevelList.forEach(v => {
      v.active = v === obj;
    });
    this.fristObj = obj.displayName;
  }


  //  协助、
  resSetFilter() {
    const that = this;
    // 将要显示的条件列表加入
    this.siftArr = [];
    this.result.filter = {};
    this.result.order = {};

    this.commonFilterTag.filterItems.forEach(element => {
      if (element.indexName && element.indexName === this.selectedIndexName) {
        that.siftArr.push(element);
      } else if (!element.indexName) {
        that.siftArr.push(element);
      }
      if (element.dropDownList && element.dropDownList.item) {
        element.dropDownList.item.forEach(e => {
          delete e.active;
        });
      }
    });

    for (let i = 0; i < this.siftArr.length; i++) {

      if (that.siftArr[i].dropDownList) {
        if (that.siftArr[i].dropDownList.displayName) {
          that.siftArr[i].title = that.siftArr[i].dropDownList.displayName;
        }
        // 条件栏目
        if (!that.siftArr[i].indexName) {
          that.siftArr[i].title = that.selectedIndexDisplayName;
        }
        // 设置默认筛选条件
        if (that.siftArr[i].type === "filter") {
          that.result.filter[that.siftArr[i].name] = that.siftArr[i].dropDownList.value;
        }

        // 设置默认排序条件
        if (that.siftArr[i].type === "order") {
          const name = that.siftArr[i].name;
          const displayName = that.siftArr[i].dropDownList.displayName;
          that.siftArr[i].dropDownList.item.forEach(element => {
            if (element.displayName === displayName) {
              const kSort = {};
              element.sorts.forEach(e => {
                kSort[e.field] = e.value;
              });
              that.result.order.sort = kSort;
            }
          });
        }
      } else if (that.siftArr[i].type === "link" && that.siftArr[i].display && that.siftArr[i].display.displayName.leng) {
        that.siftArr[i].title = that.siftArr[i].display.displayName;
        that.result.filter[that.siftArr[i].name] = that.siftArr[i].display.value;
      }
    }

  }

  // 处理点击结果
  getResult(obj) {
    const pos = JSON.parse(localStorage.getItem("position"));
    this.result.showName = sessionStorage.getItem('showName') ? sessionStorage.getItem('showName') : this.commonFilterTag.keyTag; // 新增默认值
    // 调整条件结构
    const kFilter = "filter";
    const kType = "filter";
    const kOrder = "order";
    const kLocation = "location";
    const kStrSort = "sort";
    if (this.type === "filter") {
      if (obj.min !== undefined || obj.max !== undefined) {
        (obj.min === undefined || obj.min === null) ? obj.min = "0" : obj.min = obj.min;
        // 用户输入了最小值如果手动删除最大值已与产品沟通传空串
        this.result[kFilter][this.key] = obj.min + "," + (obj.max === undefined ? "" : obj.max === null ? "" : obj.max);
      } else {
        this.result[kFilter][this.key] = obj.value;
      }
      if ((obj[kType] && obj[kType] === 1) || obj[kType] === 0) {
        this.result[kFilter][this.key] = obj;
      }
      if (this.result.showName === "#opportunity_rent") {
        if (this.result.filter.opportunity_industry_id) {
          const suitIndustry = this.result.filter.opportunity_industry_id;
          delete this.result.filter.opportunity_industry_id;
          this.result.filter.opportunity_suit_industry = suitIndustry;
        }
      } else {
        // fix by andrew.wen for 后台返回什么参数前端就post什么参数否则无法扩展复用。
        // if (this.result.filter.opportunity_suit_industry) {
        //   const industryId = this.result.filter.opportunity_suit_industry;
        //   delete this.result.filter.opportunity_suit_industry;
        //   this.result.filter.opportunity_industry_id = industryId;
        // }
      }
    } else if (this.type === kOrder) {
      if (this.result[kLocation]) {
        delete this.result[kLocation];
      }
      if (obj.displayName) {
        const kSort = {};
        // this.result[kOrder] = {
        //   value: obj.value
        // };
        if (obj.sorts) {
          obj.sorts.forEach(v => {
            kSort[v.field] = v.value;
          });
          this.result[kOrder][kStrSort] = kSort;
        }
        if (obj.needLoaction) {
          this.result[kLocation] = {
            name: "aaa",
            longitude: pos.center.lng,
            latitude: pos.center.lat
          };
        }
      } else {
        this.result[kOrder] = {
          // value: obj.value,
          sort: obj.sort
        };
      }
    }
    localStorage.setItem('siftReqConditionTag', JSON.stringify(this.result));

    // 发送前判断是否需要记录筛选条件
    const needRememberResult = { result: { filter: {}, order: {} } };
    const filterTagName = 'needRememberResult' + this.commonFilterTag.name;
    this.siftArr.forEach(v => {
      if (v.needRememberLast === true) {
        if (v.type === 'filter' && this.result.filter[v.name] !== undefined) {
          needRememberResult.result.filter[v.name] = this.result.filter[v.name];
          needRememberResult[v.name] = v.title;
          if (localStorage.getItem(filterTagName)) {
            const localObj = JSON.parse(localStorage.getItem(filterTagName));
            localObj[v.name] = needRememberResult[v.name];
            localObj.result.filter[v.name] = needRememberResult.result.filter[v.name];
            localStorage.setItem(filterTagName, JSON.stringify(localObj));
          } else {
            localStorage.setItem(filterTagName, JSON.stringify(needRememberResult));
          }
          // tslint:disable-next-line:max-line-length
        } else if (v.type === 'filter' && localStorage.getItem(filterTagName) && JSON.parse(localStorage.getItem(filterTagName)).result.filter[v.name] !== undefined) {
          this.result.filter[v.name] = JSON.parse(localStorage.getItem(filterTagName)).result.filter[v.name];
        }

        if (v.type === 'order' && this.result.order !== undefined) {
          if ('{}' !== JSON.stringify(this.result.order)) {
            needRememberResult.result.order = this.result.order;
          }
          needRememberResult[v.name] = v.title;
          if (localStorage.getItem(filterTagName)) {
            const localObj = JSON.parse(localStorage.getItem(filterTagName));
            localObj[v.name] = needRememberResult[v.name];
            if ('{}' !== JSON.stringify(needRememberResult.result.order)) {
              localObj.result.order = needRememberResult.result.order;
            } else if ('{}' !== JSON.stringify(localObj.result.order)) {
              this.result.order = localObj.result.order;
            }
            localStorage.setItem(filterTagName, JSON.stringify(localObj));
          } else {
            localStorage.setItem(filterTagName, JSON.stringify(needRememberResult));
          }
          // tslint:disable-next-line:max-line-length
        } else if (v.type === 'order' && localStorage.getItem(filterTagName) && JSON.parse(localStorage.getItem(filterTagName)).result.order !== undefined) {
          this.result.order = JSON.parse(localStorage.getItem(filterTagName)).result.order;
        }
      }
    });
    // 首次加载如果参数错误需要手动构建


    // if (this.tagData && this.tagData.currentData.tags[0].style === "appLjGeneralListTag") {
    //   if (!this.result.opportunity_plugin_id || !this.result.plugin_type_id) {
    //     const submit = this.tagData.currentData.tags[0].data.submit.content;
    //     if (submit.plugin_type_id) {
    //       this.result.opportunity_plugin_id = submit.plugin_type_id;
    //     } else {
    //       this.result.plugin_type_id = this.result.opportunity_plugin_id;
    //     }
    //   }
    // }

    // 传递筛选条件
    // this.message.sendMessage(this.result);
    this.message.sendMessageById(this.result, 'uuid');
  }

  // 点击第二层下拉列表
  chooseSecondEvent(obj) {
    obj.active = true;
    this.openFlag = false;
    this.appGlobalService.openBackdrop = false;
    this.secondLevelList.forEach(v => {
      v.active = v === obj;
    });
    this.siftArr.forEach(v => {
      if (v === this.siftObj) {
        if (obj.displayName === "全部") {
          v.title = this.fristObj;
        } else {
          v.title = obj.displayName;
        }
      }
    });
    this.getResult(obj);
  }

  // tslint:disable-next-line:use-life-cycle-interface
  ngOnDestroy(): void {
    this.message.clearMessage();
    // localStorage.removeItem('needRemberResult');
  }

  ionViewWillLeave() {
    console.log('msg----->ionViewWillLeave');
    // this.message.clearMessage();
  }

  defineArea(obj) {
    const reg = new RegExp(obj.regular);
    if (obj.min && !reg.test(obj.min)) {
      this.appGlobalService.showToast(
        "最小" + obj.title + '--' + obj.message,
        2000,
        "middle"
      );
      return false;
    }
    if (obj.max && !reg.test(obj.max)) {
      this.appGlobalService.showToast(
        "最大" + obj.title + '--' + obj.message,
        2000,
        "middle"
      );
      return false;
    }
    if (obj.min && obj.max && obj.min * 1 > obj.max * 1) {
      this.appGlobalService.showToast(
        "最小" + obj.title + "不能大于最大" + obj.title,
        2000,
        "middle"
      );
      return false;
    }
    // if (!obj.max) {
    //   this.appGlobalService.showToast("请填写最大" + obj.title, 2000, "middle");
    //   return false;
    // }
    // if (!obj.min) {
    //   this.appGlobalService.showToast("请填写最小" + obj.title, 2000, "middle");
    //   return false;
    // }
    this.chooseFirstEvent(obj);
  }

}

